#include <wiringPi.h>
#include <stdlib.h>
#include <stdio.h>
#include <mysql.h>
#include <sys/time.h>
#include <string.h>
#include <mysql/mysql.h>  

#define Trig    4
#define Echo    5



void ultraInit(void)
{
    pinMode(Echo, INPUT);  //设置端口为输入
    pinMode(Trig, OUTPUT);  //设置端口为输出
}

float disMeasure(void)
{
    struct timeval tv1;  //timeval是time.h中的预定义结构体 其中包含两个一个是秒，一个是微秒
    /*
    struct timeval
    {
        time_t tv_sec;  //Seconds.
        suseconds_t tv_usec;  //Microseconds.
    };
    */

    struct timeval tv2;
    long start, stop;
    float dis;

    digitalWrite(Trig, LOW);
    delayMicroseconds(2);

    digitalWrite(Trig, HIGH);
    delayMicroseconds(10);      //发出超声波脉冲
    digitalWrite(Trig, LOW);

    while(!(digitalRead(Echo) == 1));
    gettimeofday(&tv1, NULL);           //获取当前时间 开始接收到返回信号的时候

    while(!(digitalRead(Echo) == 0));
    gettimeofday(&tv2, NULL);           //获取当前时间  最后接收到返回信号的时候
    /*
    int gettimeofday(struct timeval *tv, struct timezone *tz);
    The functions gettimeofday() and settimeofday() can get and set the time as well as a timezone.
    The use of the timezone structure is obsolete; the tz argument should normally be specified as NULL.
    */
    start = tv1.tv_sec * 1000000 + tv1.tv_usec;   //微秒级的时间
    stop  = tv2.tv_sec * 1000000 + tv2.tv_usec;

    dis = (float)(stop - start) / 1000000 * 34000 / 2;  //计算时间差求出距离

    return dis;
}

int main(void)
{
    float dis;
float *sj;



    if(wiringPiSetup() == -1){ //如果初始化失败，就输出错误信息 程序初始化时务必进行
        printf("setup wiringPi failed !");
        return 1;
    }

    ultraInit();

    while(1){

	//数据库操作
        MYSQL *conn_ptr;
        int res;
        conn_ptr = mysql_init(NULL);
        if (!conn_ptr) {
            printf("mysql_init failed\n");
            return EXIT_FAILURE;
        }


        dis = disMeasure();


        printf("distance = %0.2f cm\n",dis);


float p=1.222;
char dstr[20];
sprintf(dstr,"%.2lf",dis);//将dis赋值给dstr
//printf("呀呀呀%s\n",dstr);

//解决插入变量问题
char sqlstr[1024];
char sqlsfbj[1024];
//sprintf(sqlsfbj, "No alarm");

if(dis>30){
int len = sprintf(sqlstr, "INSERT INTO csbsjb VALUES('%f','Alarm',curtime());", dis);
}
else{
int len = sprintf(sqlstr, "INSERT INTO csbsjb VALUES('%f','No alarm',curtime());", dis);

}

	//插入数据  csbsj表格里有(jl,sfbj,timt) (距离，是否报警，时间)两列
  	 conn_ptr = mysql_real_connect(conn_ptr, "localhost", "root", "svh123456", "csb", 0, NULL, 0);
        if (conn_ptr) {
            res = mysql_query(conn_ptr,sqlstr ); //可以把insert语句替换成delete或者update语句，都一样的
                if (!res) { //输出受影响的行数
                printf("Inserted %lu rows\n",(unsigned long)mysql_affected_rows(conn_ptr));
            } else { //打印出错误代码及详细信息
                fprintf(stderr, "Insert error %d: %sn",mysql_errno(conn_ptr),mysql_error(conn_ptr));
            }
        } else {
            printf("Connection failed\n");
        }
if(dis>30){

    MYSQL_RES *res1;
    MYSQL_ROW row1; 
	int t;
    char query[50] = {0};
    sprintf(query, "SELECT * FROM csbsjb");
 t = mysql_real_query(conn_ptr, query, strlen(query));  //如果查询成功，返回0。如果出现错误，返回非0值。


    res1 = mysql_store_result(conn_ptr);
    while (row1 = mysql_fetch_row(res1)) {  
        for(t = 0; t < mysql_num_fields(res1); t++) {  
            printf("%s\t", row1[t]);  
        }  
        printf("\n");
    }  
    mysql_free_result(res1);



}

if(dis>30){


wiringPiSetup();
    int i = 0;
    pinMode(1,OUTPUT);
    for(i=0;i<5;i++)
    {
        //printf("turn off led\n");
        digitalWrite(1,HIGH);
        delay(500);
        //printf("turn on led\n");
        digitalWrite(1,LOW);
        delay(500);
	if(i==4){

        mysql_close(conn_ptr);
        return EXIT_SUCCESS;
	}
    }

}

        delay(1000);

    }

    return 0;
}